﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using Xiaov.SmartWeb.Model;

namespace Xiaov.SmartWeb.Application.ZNPT
{
  public partial class ReportWord : BasePage
  {
    //word编码
    private string _wbm;
    public string Wbm
    {
      get
      {
        if (Request.QueryString["wbm"] != null)
          _wbm = Request.QueryString["wbm"].ToString().ToUpper();
        else
          _wbm = "test";
        return _wbm;
      }
    }

    //菜单的ID
    private string _moduleid;
    public string ModuleID
    {
      get
      {
        if (Request.QueryString["mid"] != null)
        {
          _moduleid = Request.QueryString["mid"].ToString();
        }
        else
        {
          _moduleid = "0000";
        }
        return _moduleid;
      }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      //PM_Filter();
      //Response.Write("<div id='mydiv' >");
      //Response.Write("_");
      //Response.Write("</div>");
      //Response.Write("<script>mydiv.innerText = '';</script>");
      //Response.Write("<script language=javascript>;");
      //Response.Write("var dots = 0;var dotmax = 10;function ShowWait()");
      //Response.Write("{var output; output = '正在装载页面';dots++;if(dots>=dotmax)dots=1;");
      //Response.Write("for(var x = 0;x < dots;x++){output += '·';}mydiv.innerText =  output;}");
      //Response.Write("function StartShowWait(){mydiv.style.visibility = 'visible'; ");
      //Response.Write("timeID =window.setInterval('ShowWait()',1000);}");
      //Response.Write("function HideWait(){mydiv.style.visibility = 'hidden';");
      //Response.Write("window.clearInterval(timeID );}");
      //Response.Write("StartShowWait();</script>");
      //Response.Flush();//这一句是最关键的

      if (!IsPostBack)
      {
        //绑定下拉框的单位、年度、月度
        BindDDL();

        //标题名

        string strSQL = "select * from zn_docbm";
        DataTable dt = Maticsoft.DBUtility.DbHelperOra.Query(strSQL).Tables[0];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
          string strName = dt.Rows[i]["docmc"].ToString();
          string strDM = dt.Rows[i]["docbm"].ToString();
          ListItem item = new ListItem();
          item.Text = strName;
          item.Value = strDM;

          ListBox1.Items.Add(item);
        }

        //      string sql_title = "select docmc from zn_docbm t where t.docbm = '" + Wbm.ToUpper().ToString() + "' ";
        //      lbtitle.Text = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql_title).ToString();

        //当前附件
        //     BindFJ();
      }

    }

    //显示当前附件
    protected void BindFJ()
    {
      string v_docbm, v_dwbm, v_nf, v_yf;

      v_docbm = Wbm;
      v_dwbm = ddl_Owner.SelectedValue.ToString();
      v_nf = ddl_Year.SelectedValue.ToString();
      v_yf = ddl_Month.SelectedValue.ToString();

      string sql_fj;
      sql_fj = "select filename from zn_docfilename where nf = '" + v_nf + "' and yf = '" + v_yf + "' and dwbm = '" + v_dwbm + "' and docbm = '" + v_docbm + "'";

      try
      {
        Label1.Text = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql_fj).ToString();
      }
      catch
      {
        Label1.Text = "";
      }
    }

    #region 绑定下拉菜单
    protected void BindDDL()
    {
      try
      {
        //Statistics.UI.DDL.BindDDL(ddl_Owner, ddl_Year, ddl_Month, PUser.USERDEPT, true);
        BindDDL_Owner();
        BindNF();
      }
      catch (Exception ex)
      {
        throw ex;

      }

      //从cookies获取默认值
      //if (Request.Cookies["UserSelectInfo"] != null)
      //{
      //  ddl_Owner.SelectedValue = Request.Cookies["UserSelectInfo"]["DW"];
      //  ddl_Year.SelectedValue = Request.Cookies["UserSelectInfo"]["NF"];
      //  ddl_Month.SelectedValue = Request.Cookies["UserSelectInfo"]["YF"];
      //}
    }
    #endregion

    protected void BindDDL_Owner()
    {
      string yhdw = PUser.USERDEPT;
      ddl_Owner.DataSource = Maticsoft.DBUtility.DbHelperOra.Query("select y.dwmc,y.dwbm from dwbmb y where dwbm like '" + yhdw + "%'");
      ddl_Owner.DataTextField = "DWMC";
      ddl_Owner.DataValueField = "DWBM";
      ddl_Owner.DataBind();
    }
    protected void BindNF()
    {
      int startyear = int.Parse(System.Configuration.ConfigurationManager.AppSettings["startyear"].ToString());
      int end = DateTime.Now.Year + 1;
      for (int i = startyear; i <= end; i++)
      {
        ListItem li = new ListItem();
        li.Text = i.ToString();
        li.Value = i.ToString();
        ddl_Year.Items.Add(li);
      }
      ddl_Year.SelectedValue = DateTime.Now.Year.ToString();
      ddl_Year.SelectedValue = DateTime.Now.Month.ToString();
    }

    public static void BindDDL_YearAndMonth(DropDownList ddlYear, DropDownList ddlMonth, string tableName)
    {
      int thisyear = DateTime.Now.Year;
      int preyear = 2010;
      for (int year = preyear; year <= thisyear + 10; year++)
      {
        ddlYear.Items.Add(year.ToString());
      }

      string sql = "select t.doczq from zn_docbm t where t.docbm='" + tableName.ToUpper() + "'";
      object o = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql);
      int thismonth = DateTime.Now.Month;
      if (o != null)
      {
        switch (o.ToString())
        {
          case "月度":
            for (int month = 1; month <= 12; month++)
            {
              ddlMonth.Items.Add(month.ToString());
            }
            break;
          case "年度":
            ddlMonth.Items.Add(new ListItem("12", "12"));
            break;
          case "季度":
            ddlMonth.Items.Add(new ListItem("一季度", "3"));
            ddlMonth.Items.Add(new ListItem("二季度", "6"));
            ddlMonth.Items.Add(new ListItem("三季度", "9"));
            ddlMonth.Items.Add(new ListItem("四季度", "12"));
            break;
          default:
            for (int month = 1; month <= 12; month++)
            {
              ddlMonth.Items.Add(month.ToString());
            }
            break;

        }
      }
      ddlYear.SelectedValue = thisyear.ToString();
      ddlMonth.SelectedValue = (thismonth - 1).ToString();
    }

    protected void ddl_Owner_SelectedIndexChanged(object sender, EventArgs e)
    {
      BindFJ();
    }

    protected void ddl_Year_SelectedIndexChanged(object sender, EventArgs e)
    {
      BindFJ();
    }

    protected void ddl_Month_SelectedIndexChanged(object sender, EventArgs e)
    {
      BindFJ();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
      //string filepatht = "~/ZNPT/report/矿区统计分析.doc";
      //Response.Redirect(filepatht);
      //return;


      //    Microsoft.Office.Interop.Word._Application appWord = new Microsoft.Office.Interop.Word.ApplicationClass();
      //    Microsoft.Office.Interop.Word._Document docFile = null;

      //模板名称
      if (ListBox1.SelectedIndex == -1)
      {
        return;
      }
      string sql_doc = "select dotmc from zn_docbm where docbm = '" + ListBox1.SelectedValue + "'";
      string DotName;
      DotName = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql_doc).ToString();

      sql_doc = "select docbm from zn_docbm where docbm = '" + ListBox1.SelectedValue + "'";
      string docbm;
      docbm = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql_doc).ToString();

      //传入变量，将来用实际参数替代.word编码，单位编码，年份，月份
      string v_docbm, v_dwbm, v_nf, v_yf;

      v_docbm = Wbm;
      v_dwbm = ddl_Owner.SelectedValue.ToString();
      v_nf = ddl_Year.SelectedValue.ToString();
      v_yf = ddl_Month.SelectedValue.ToString();

      OracleParameter[] parameters ={     
                    new OracleParameter("p_docBM",OracleType.VarChar,100),
                    new OracleParameter("p_dwbm",OracleType.VarChar,100),
                    new OracleParameter("p_nf",OracleType.VarChar,100),
                    new OracleParameter("p_yf",OracleType.VarChar,100),
                    new OracleParameter("p_user",OracleType.VarChar,100),
                    };

      parameters[0].Value = docbm;
      parameters[1].Value = v_dwbm;
      parameters[2].Value = v_nf;
      parameters[3].Value = v_yf;
      parameters[4].Value = PUser.LOGINNAME;


      OracleDataReader dr = Maticsoft.DBUtility.DbHelperOra.RunProcedure("p_doc_qs_all", parameters);
      dr.Close();



      //     DataSet ds = Maticsoft.DBUtility.DbHelperOra.RunProcedure("p_doc_qs_all", parameters,"newtable");

      //     Maticsoft.DBUtility.DbHelperOra.RunProcedure()

      Dictionary<string, string> wordTexts = new Dictionary<string, string>();
      string strSQL = "select * from SETT_DAILYTEST where CURUSER='" + PUser.LOGINNAME + "'";
      DataSet ds = Maticsoft.DBUtility.DbHelperOra.Query(strSQL);

      wordTexts.Clear();
      foreach (DataRow drow in ds.Tables[0].Rows)
      {//User,TAGINFO,JSDATA
        string strTag = drow["TAGINFO"].ToString();
        string strData = drow["JSDATA"].ToString();
        wordTexts.Add(strTag, strData);
      }


      WordMLHelper Word = new WordMLHelper();

      string strFilePath = System.Web.HttpContext.Current.Server.MapPath("~") + "ZNPT/" + DotName;
      Word.CreateXmlDom(strFilePath);
      string name = ddl_Owner.SelectedValue + "_" + ddl_Year.SelectedValue + "_" + ddl_Month.SelectedValue;
      //HttpContext.Current.Response.Write("<javascript>window.self.reload();</javascript>"); 
      Word.GenNewWordXML(strFilePath, wordTexts, name);



      // this.ClientScript.RegisterStartupScript(this.GetType(), this.Title, "alert('添加成功!');window.close();window.opener.location.reload();", true); 

      /*   
         //try
         //{
         appWord.Visible = false;
         object objTrue = true;
         object objFalse = false;

         object objTemplate = Server.MapPath(@"dot\\" + DotName);//模板路径
         object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;
         docFile = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
         //第一步生成word文档
         //定义书签变量


         //查询该word用的取数配置信息
         string sql_query;
         sql_query = @"select * from zn_docjsxx a where a.docbm = '" + v_docbm
             + "' and (replace(replace(a.nf,\'[\',\'\'),\']\',\'\') = '" + v_nf
             + "' or a.nf is null) and (replace(replace(a.yf,\'[\',\'\'),\']\',\'\') = '" + v_yf
             + "' or a.yf is null) order by a.docjsxxid";

         //装入DataReader中
         //OracleDataReader mydr = (OracleDataReader)Maticsoft.DBUtility.DbHelperOra.ExecuteReader(sql_query);
         DataTable dtWord = Maticsoft.DBUtility.DbHelperOra.Query(sql_query).Tables[0];
         //循环DataReader，调用过程取数返回数值           
         for (int i = 0; i < dtWord.Rows.Count; i++)
         {
           //书签插入的方式
           //object OSQ = mydr["SQMC"]; //书签名称
           //decimal v_sj;
           //v_sj = 0;

           //计算描述
           string JSMS = dtWord.Rows[i]["JSMS"].ToString();
           //替换的字符的方式
           object Replace_String = dtWord.Rows[i]["SQMC"];       //要替换的字符 
           object ReplaceWith = 0;             //最终替换成的字符
           object ms = System.Type.Missing;

           //计算信息ID
           Int32 JSXXID = Convert.ToInt32(dtWord.Rows[i]["DOCJSXXID"]);
           if (!string.IsNullOrEmpty(JSMS))
           {
             //调用过程取出值               
             OracleParameter[] parameters ={     
                       new OracleParameter("p_docjsxxid",OracleType.Number,10),
                       new OracleParameter("p_jsms",OracleType.VarChar,100),
                       new OracleParameter("p_dwbm",OracleType.VarChar,100),
                       new OracleParameter("p_nf",OracleType.VarChar,100),
                       new OracleParameter("p_yf",OracleType.VarChar,100),
                       new OracleParameter("p_sj",OracleType.Number,10)
                       };

             parameters[0].Value = JSXXID;
             parameters[1].Value = JSMS;
             parameters[2].Value = v_dwbm;
             parameters[3].Value = v_nf;
             parameters[4].Value = v_yf;
             parameters[5].Direction = System.Data.ParameterDirection.Output;
             //parameters[5].Value = v_sj;

             //执行存储过程
             OracleDataReader mydr_pro = Maticsoft.DBUtility.DbHelperOra.RunProcedure("p_doc_qs", parameters);
             mydr_pro.Close();
             try
             {
               //v_sj = Convert.ToDecimal(parameters[5].Value);
               ReplaceWith = parameters[5].Value.ToString();
             }
             catch
             {
               //v_sj = 0;
               ReplaceWith = 0;
             }
           }
           //给书签赋值---书签方式插入数值
           //docFile.Bookmarks.get_Item(ref OSQ).Range.Text = v_sj.ToString();

           //全文替换字符的方式---全文替换会丢格式
           //docFile.Content.Text = docFile.Content.Text.Replace("单击“添加”按钮","hahahaha"); ---全文替换会丢格式               

           //替换字符
           object Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;//设置替换方式:一，全部替换；二，只替换一个；三，一个都不替换。
           docFile.Content.Find.Execute(ref Replace_String, ref ms, ref ms, ref ms, ref ms, ref ms, ref ms, ref ms, ref ms, ref ReplaceWith, ref Replace, ref ms, ref ms, ref ms, ref ms);

         }

         //删除文件
         //if (File.Exists("文件处理单.doc"))
         //{
         //    File.Delete("文件处理单.doc"); //删除文件，别忘了检查一下有没有这个文件 
         //} 

         //第四步 生成word
         DateTime dt = DateTime.Now;
         object filename = Server.MapPath("report\\") + v_dwbm.ToString() + v_docbm.ToString() + v_nf.ToString() + v_yf.ToString() + ".doc";
         object miss = System.Reflection.Missing.Value;
         docFile.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
         object missingValue = Type.Missing;
         object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
         docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
         appWord.Quit(ref miss, ref miss, ref miss);
         docFile = null;
         appWord = null;

         //将文件名保存到数据库对应的单位、年份、月份、word编码中
         //string sql_del_doc;
         //sql_del_doc = "delete from zn_docfilename where nf = " + v_nf + " and yf = " + v_yf + " and dwbm = '" + v_dwbm + "' and docbm = '" + v_docbm + "'";
         //Maticsoft.DBUtility.DbHelperOra.ExecuteSql(sql_del_doc);
         //string sql_insert_doc;
         //sql_insert_doc = "insert into zn_docfilename (NF,YF,DWBM,DOCBM,FILENAME) values (" + v_nf + "," + v_yf + ",'" + v_dwbm + "','" + v_docbm + "','" + filename + "')";
         //Maticsoft.DBUtility.DbHelperOra.ExecuteSql(sql_insert_doc);

         //打开该文件
         string filepath = "~/ZNPT/report/" + v_dwbm.ToString() + v_docbm.ToString() + v_nf.ToString() + v_yf.ToString() + ".doc";
         Response.Redirect(filepath);
         //System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("utf-8");
         //System.Web.HttpContext.Current.Response.Charset = "UTF-8";
         //HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=a.doc");
         //HttpContext.Current.Response.ContentType = "application/ms-word";
         //Response.Write(Doc2Text(filepath));
         //}
         //catch (Exception ex)
         //{
         //    //捕捉异常，如果出现异常则清空实例，退出word,同时释放资源
         //    string aa = e.ToString();
         //    object miss = System.Reflection.Missing.Value;
         //    object missingValue = Type.Missing;
         //    object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
         //    docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
         //    appWord.Quit(ref miss, ref miss, ref miss);
         //    docFile = null;
         //    appWord = null;
         //    throw ex;
         //}*/
    }

    //保存
    protected void Button2_Click(object sender, EventArgs e)
    {
      string v_docbm, v_dwbm, v_nf, v_yf;

      v_docbm = Wbm;
      v_dwbm = ddl_Owner.SelectedValue.ToString();
      v_nf = ddl_Year.SelectedValue.ToString();
      v_yf = ddl_Month.SelectedValue.ToString();

      //将文件名保存到数据库对应的单位、年份、月份、word编码中
      string sql_del_doc;
      sql_del_doc = "delete from zn_docfilename where nf = " + v_nf + " and yf = " + v_yf + " and dwbm = '" + v_dwbm + "' and docbm = '" + v_docbm + "'";
      Maticsoft.DBUtility.DbHelperOra.ExecuteSql(sql_del_doc);
      string sql_insert_doc;
      sql_insert_doc = "insert into zn_docfilename (NF,YF,DWBM,DOCBM,FILENAME) values (" + v_nf + "," + v_yf + ",'" + v_dwbm + "','" + v_docbm + "','" + txtnr.Value.ToString() + "')";
      Maticsoft.DBUtility.DbHelperOra.ExecuteSql(sql_insert_doc);
      Label1.Text = txtnr.Value.ToString();
    }

    public string Doc2Text(string docFileName)
    {
      //实例化COM
      Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
      object fileobj = docFileName;
      object nullobj = System.Reflection.Missing.Value;
      //打开指定文件（不同版本的COM参数个数有差异，一般而言除第一个外都用nullobj就行了）
      Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref fileobj, ref nullobj, ref nullobj,
          ref nullobj, ref nullobj, ref nullobj,
          ref nullobj, ref nullobj, ref nullobj,
          ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj
          );
      //取得doc文件中的文本
      string outText = doc.Content.Text;
      //关闭文件
      object missingValue = Type.Missing;
      object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
      doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
      //关闭COM
      wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
      //返回
      return outText;
    }
  }
}